package com.xlh.controller;

import com.xlh.common.Result;
import com.xlh.constant.UserConstant;
import com.xlh.entity.ImageCode;
import com.xlh.util.VerifyCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 未授权
 * <p>
 * Created by lx on 2019/1/25.
 */
@Api(tags = "UnauthorizedController", description = "未授权")
@RestController
@RequestMapping("/unauthorized")
public class UnauthorizedController {


    @ApiOperation("是否需要获取验证码")
    @GetMapping("/image-code/show")
    public Result<Boolean> getImageCodeIsShow(HttpServletRequest request) {
        Integer sessionFailNum = (Integer) request.getSession().getAttribute(UserConstant.CODE_FAIL_NUM);
        return Result.success(sessionFailNum == null ? false : true);
    }


    @ApiOperation("获取图片验证码")
    @GetMapping("/image-code")
    public void getImageCode(HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(required = false, defaultValue = "100") Integer width,
                             @RequestParam(required = false, defaultValue = "40") Integer height) {

        String code = VerifyCodeUtils.generateVerifyCode(4);
        try {
            VerifyCodeUtils.outputImage(width, height, code, response);
        } catch (IOException e) {

        }
        // 将验证码放置session中
        HttpSession session = request.getSession(true);
        session.removeAttribute(UserConstant.CODE_SESSION_KEY);
        session.setAttribute(UserConstant.CODE_SESSION_KEY, new ImageCode(code, UserConstant.CODE_EXPIRED_TIME));
    }


}
